<template>
  <div class="homeContent">
      <!-- v-for循环服务类别 -->
      <div class="top-container pt40 pl300 pr300">
          <div class="row-start-col-center wrap">
              <div v-for="item,index in serviceTypeData" :key="index" class="mt10 shopTypeCard" @click="openNew(item)">
                  <div class="row-center-col-center showMouse" :class="backgroundClass(item,index)">
                      <div class="icon showMouse">
                          <icon-font size="30"  :class="[item.icon]" />
                      </div>
                      <div class="ml10 fs16 showMouse">
                        <span>{{item.productTypeName}} </span>
                      </div>
                  </div>
              </div>
          </div>
          <div class="card-detail mt25 row-start-col-center pd20">
            <div v-if="selectedItem">
                <p><span class="fwbold color-primary">【{{selectedItem.productTypeName}}】</span></p>
                <p v-html="selectedItem?.productTypeDetail || serviceTypeData[0]?.productTypeDetail"> </p>
            </div>
          </div>
     </div>
     <div class="bg-gray pl300 pr300 pt20 pb20 relposition">
            <!-- 名称搜索 -->
            <div class="row-spaceb-col-center">
                <div class="fs14">
                    <span>共为您找到<span class="color-primary">{{total}}</span>个相关信息</span>
                </div>
                <div class="row-start">
                    <el-input size="small" clearable placeholder="请输入服务需求关键字" @keyup.enter.native="searchKey" v-model="searchKeyword" class="input-with-select">
                    <el-button slot="append" icon="el-icon-search" @click="searchKey"></el-button>
                    </el-input>
                    <el-button size="small" plain class="ml10" @click="searchAll">全部</el-button>
                </div>
            </div>
            <!-- v-for循环生成卡片式服务列表 -->
            <el-empty v-if="cardList.length === 0" :image-size="200"></el-empty>
            <div v-else>
                <div class="width-19">
                    <div v-for="item,index in cardList" :key="index" class="mt20 card-shadow pd20 bg-white">
                        <div class="relposition">
                            <div class="row-spaceb">
                                 <div class="row-start-col-center">
                                     <div class="card-title">技术创新</div>
                                     <div class="fs16 fwbold">{{item.requirement}}</div>
                                 </div>
                                 <div>
                                    <span class="fs14">预算金额: <span class="fs20 color-red fwbold">{{item.budget > 0 ? `${item.budget}元` : '需服务商报价'}}</span></span>
                                 </div>
                            </div>
                        </div>
                        <div class="mt20 mb20 row-start fs14 color-grey">
                            <div>需求分类：{{item.requirementTypeName}}</div>
                            <div class="ml30">联系方式：{{item.companyPhone}}</div>
                            <div class="ml30">发布时间：{{item.publishTime ? moment(item.publishTime).format('YYYY-MM-DD HH:mm:ss') : '--'}}</div>
                        </div>
                        <div class="row-spaceb card-content">
                            <div class="row-start">
                                <div><img src="@/assets/image/requireIcon.png"></div>
                                <div class="ml30 fs14 color-grey">
                                    <div v-if="item.serviceCount > 0">目前已有<span class="color-primary">{{item.serviceCount}}</span>家服务商申请对接</div>
                                    <div v-else>正在等待对接</div>
                                    <div class="mt10">若您能接近该需求，请留下联系方式等待需求方与您联系</div>
                                </div>
                            </div>
                            <div class="mt10">
                                <el-button v-if="item.status === 1"  type="primary" round size="small" @click="openRequieDetail(item.requirementId)">我要对接</el-button>
                                <el-button v-else-if="item.status === 4" type="text" size="small" @click="openRequieDetail(item.requirementId)">等待对接</el-button>
                                <el-button v-else-if="item.status === 2" type="success" round size="small" @click="openRequieDetail(item.requirementId)">已对接</el-button>
                                <el-button v-else-if="item.status === 3" type="success" round size="small" @click="openRequieDetail(item.requirementId)">已解决</el-button>
                            </div>
                        </div>
                        <div class="mt20 row-spaceb">
                            <div></div>
                            <div>
                                <el-button type="text" @click="openRequieDetail(item.requirementId)">查看需求详情 >></el-button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="width-4 ml20 mt20 requirment">
                  <div class="advertisement">
                      <el-button type="primary" plain size="small" class="button1" @click="creatRequirement">发布需求</el-button>
                  </div>
            </div>
    </div>
    <!-- 需要详情 -->
    <el-dialog title="需求详情" :visible.sync="dialogVisible" width="860px" custom-class="my-dialog" append-to-body :close-on-click-modal="false">
        <div class="ml20">
            <div class="row-start">
                <div class="left-border"></div>
                <div class="ml5 fs16 fwbold">基本信息</div>
            </div>
            <el-descriptions class="mt20" title="" :column="2" border>
                <el-descriptions-item>
                    <template slot="label">
                        <i class="el-icon-user"></i>
                        需求名称
                    </template>
                    {{serviceData.requirement}}
                </el-descriptions-item>
                <el-descriptions-item>
                    <template slot="label">
                        <i class="el-icon-date"></i>
                        发布时间
                    </template>
                    {{serviceData.publishTime ? moment(serviceData.publishTime).format('YYYY-MM-DD HH:mm:ss') : '-'}}
                </el-descriptions-item>
                <el-descriptions-item>
                    <template slot="label">
                        <i class="el-icon-folder-opened"></i>
                        需求分类
                    </template>
                    {{serviceData.requirementTypeName}}
                </el-descriptions-item>
                <el-descriptions-item>
                    <template slot="label">
                        <i class="el-icon-coin"></i>
                        预算金额
                    </template>
                    <el-tag size="small">{{serviceData.budget  > 0 ? `${serviceData.budget}元` : '需服务商报价'}}</el-tag>
                </el-descriptions-item>
                <el-descriptions-item>
                    <template slot="label">
                        <i class="el-icon-phone"></i>
                        联系方式
                    </template>
                    {{serviceData.companyPhone}}
                </el-descriptions-item>
                <el-descriptions-item>
                    <template slot="label">
                        <i class="el-icon-finished"></i>
                        对接状态
                    </template>
                    目前已有{{serviceData.serviceCount || 0}}家服务商对接
                </el-descriptions-item>
                <el-descriptions-item>
                    <template slot="label">
                        <i class="el-icon-office-building"></i>
                        需求企业
                    </template>
                    {{serviceData.companyName}}
                </el-descriptions-item>
            </el-descriptions>
        </div>
        <div class="ml20 mt30">
            <div class="row-start">
                <div class="left-border"></div>
                <div class="ml5 fs16 fwbold">需求内容</div>
            </div>
            <div class="mt20">
              <el-input disabled type="textarea" :rows="7" placeholder="请输入需求内容" v-model="serviceData.requirementDesc" maxlength="500" show-word-limit></el-input>
            </div>
        </div>
        <div class="tc mt20">
           <el-button v-if="serviceData.status == 1" type="primary" size="medium" class="ml20 mt20" @click="gotoConnect">我要对接</el-button>
           <div v-else-if="serviceData.status == 4" class="ml20 mt20 color-primary">等待对接</div>
           <el-button v-else-if="serviceData.status == 2" type="primary" size="medium" class="ml20 mt20" @click="() => { dialogVisible = false }">已对接</el-button>
           <el-button v-else-if="serviceData.status == 3" type="primary" size="medium" class="ml20 mt20" @click="() => { dialogVisible = false }">已解决</el-button>
        </div>
    </el-dialog>
    <!-- 需要认证提示 -->
    <el-dialog title="对接确认" :visible.sync="tipVisible" width="525px" custom-class="my-dialog">
        <el-alert
            title="广西制造业企业培优育强服务券平台对企业需求做合规性检查，请服务商对接需求时做进一步核验"
            :closable="false"
            type="warning"
            effect="dark">
        </el-alert>
        <div class="mt20" >确认对接后，可查看发布需求企业的联系方式，双方可进一步线下沟通以解决问题。请确认是否对接?</div>
        <div style="text-align: right;margin-top: 30px;">
        <el-button type="info" size="medium" @click="tipVisible = false">暂不对接</el-button>
        <el-button v-loading="applyLoading"  type="primary" size="medium"
            @click="confirmConnect()">确认对接</el-button>
        </div>
    </el-dialog>
  </div>
</template>

<script>
import { requirementPage,getProductTypeList,requirementDetail, requirementApply , userinfo } from '@/api/homeApi'
import moment from 'moment';
import { mapGetters } from 'vuex'
import {getToken} from "@/utils/auth";
import {MessageBox} from 'element-ui'
export default {
  name: 'productList',
  components: {

  },
  data () {
    return {
        moment,
       searchKeyword: null,
       selectedItems: [],
       selectedItem: {
        productTypeName:'企业诊断'
       },
       previousSelectedItem: {
        productTypeName:'企业诊断'
       },
       typeList:[
            {name:'企业诊断',icon:'icon-a-01qiyezhenduan',type:1},
            {name:'数字化转型',icon:'icon-a-03shuzihuazhuanxing', type:2},
            {name:'技术创新',icon:'icon-a-05jishuchuangxin',type:3},
            {name:'管理咨询',icon:'icon-a-07guanlizixun',type:4},
            {name:'市场开拓',icon:'icon-a-09shichangkaituo',type:5},
            {name:'企业上市',icon:'icon-a-11qiyeshangshi',type:6},
            {name:'融资服务',icon:'icon-a-02rongzifuwu',type:7},
            {name:'检测认证',icon:'icon-a-04jianyanjiance',type:8},
            {name:'法律服务',icon:'icon-a-06falvfuwu',type:9},
            {name:'培训服务',icon:'icon-a-08peixunfuwu',type:10},
            {name:'人力资源',icon:'icon-a-10renliziyuan',type:11},
            {name:'其他服务',icon:'icon-a-12qita',type:12},
       ],
       // 生成一个卡片式数组，包含12个元素，包含服务价格/单位、服务名称、服务评分，交易次数、服务券类型，服务头图
        cardList:[
          // {price:Math.floor(Math.random()*100),name:'服务名称1',score:Math.floor(Math.random()*5),tradeNum:Math.floor(Math.random()*100),type:'通用券',img:'@/assets/image/service1.png'}
        ],
        currentPage: 1,
        pageSize: 100,
        total: 10,
        selectedSortOption:1,
        serviceTypeData:[],
        orderBy:0,
        isAsc:true,
        previousSortOption: 1,
        status: 0,
        dialogVisible: false,
        tipVisible: false,
        serviceData: {
            productName: '',
            productTypeId: '',
            servicePrice: '',
            marketPrice: '',
            textarea:''
        },
        statusList:[
            {label:'我要对接',value:1},
            {label:'已对接',value:2},
            {label:'已解决',value:3},
            {label:'等待对接',value:4},
        ],
        applyLoading: false
    }
  },
  created () {
    // 获取服务类型
    this.getProductType()
    this.getRequirementPage()
  },
  computed: {
    ...mapGetters([
      'userInfo'
    ]),
  },
  methods: {
     //statusList 字典映射
     gotoConnect(){
        if(!getToken()){
              MessageBox.confirm('此功能需要登录后才能使用，是否前往登录？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(() => {
                // 用户点击了确定按钮，导航到登录页面
                this.$router.push({ path: '/login'})
              }).catch(() => {
                // 用户点击了取消按钮
              });
        } else {
           if(!this.userInfo?.isCompanyService){
              MessageBox.confirm('此功能需要入驻服务商后才能使用，是否前往申请？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(() => {
                // 用户点击了确定按钮，导航到登录页面
                this.$router.push({ name: '申请入驻平台'})
              }).catch(() => {
                // 用户点击了取消按钮
              });
           } else{
            this.tipVisible = true 
           }
        }
         
     },
     getRequirementPage(){
        requirementPage({pageNo:this.currentPage,pageNum:this.pageSize}).then(res=>{
          if(res.code === 200){
            this.cardList = res.rows
            this.total = res.total
          }
        })
     },
      backgroundClass(item,index) {
          const isSelected = this.selectedItems.includes(item);
          if (isSelected) {
            if(item.id > 10) {return [`backgrounds${item.id-10}`,'h100p']};
            return [`backgrounds${item.id}`,'h100p'];
          } else if(index >= 10){
            return [`background${index-9}`,'h100p'];
          } else {
            return [`background${index+1}`,'h100p'];
          }
      },
      setDefaultImage(event) {
        event.target.src = require('@/assets/image/error.jpg');
      },
      creatRequirement(){
        userinfo().then(res => {
          if(res.code === 200) {
            this.$router.push({name:'发布需求'})
          }
        })
      },
      openRequieDetail(id){
        this.dialogVisible = true
        requirementDetail({requirementId:id}).then(res => {
            if(res.code == 200){
               this.serviceData = res.data
            }
        })
      },
      confirmConnect(){
        this.applyLoading = true
        requirementApply({requirementId:this.serviceData.requirementId}).then(res => {
           if(res.code == 200){
                this.$message({
                type: 'success',
                message: '对接需求成功!'
                });
              this.tipVisible = false
              requirementDetail({requirementId:this.serviceData.requirementId}).then(res => {
                  if(res.code == 200){
                    this.serviceData = res.data
                  }
              })
              this.getRequirementPage()
           }
        }).finally(() => {
            this.applyLoading = false
        }) 
      },
      searchKey(){
        requirementPage({q:this.searchKeyword,pageNo:this.currentPage,pageNum:this.pageSize}).then(res=>{
          if(res.code === 200){
            this.cardList = res.rows
            this.total = res.total
          }
        })
      },
      searchAll(){
        this.searchKeyword = '';
        this.getRequirementPage()
      },
      getProductType() {
        getProductTypeList({level:2}).then(res => {
          if (res.code === 200) {
            this.serviceTypeData = res.data.map((item,index) => {
              return {
                ...item,
                icon: this.typeList[index].icon,
                id: index+1,
              }
            });
          }
        })
      },
      clearSearch() {
        this.searchKeyword = '';
        // 在这里添加你的搜索逻辑
      },
      openNew(item) {
        if (this.previousSelectedItem === item) {
          // Step 3: If the current item is the same as the previous, deselect
          this.selectedItem = null;
          this.previousSelectedItem = null; // Clear the previous selection
        } else {
          // Step 4: If the current item is different, select it and update previousSelectedItem
          this.selectedItem = item;
          this.previousSelectedItem = item; // Update the previous selection
        }
          // Prepare query parameters
        let queryParams = {
          q: this.searchKeyword,
          pageNo: this.currentPage,
          pageNum: this.pageSize,
        };
        if (this.selectedItem) {
          queryParams.requirementTypeId = this.selectedItem.productTypeId;
        }
        requirementPage(queryParams).then(res=>{
          if(res.code === 200){
            this.cardList = res.rows
          }
        })
        // 其他的代码...
      },
      handleSizeChange(val) {
        console.log(`每页 ${val} 条`);
        this.pageSize = val;
        this.search()
      },
      handleCurrentChange(val) {
        console.log(`当前页: ${val}`);
        this.currentPage = val;
        this.search()
      },
    openNew(item) {
      const index = this.selectedItems.indexOf(item);
      if (index !== -1) {
        // If the item is already selected, deselect it
        this.selectedItems.splice(index, 1);
        this.selectedItem = this.selectedItems.length > 0 ? this.selectedItems[this.selectedItems.length - 1] : null;
      } else {
        // If the item is not selected, add it to the selection
        this.selectedItems.push(item);
        this.selectedItem = item;
      }
        
      // Prepare query parameters
      let queryParams = {
        pageNo: this.currentPage,
        pageNum: this.pageSize
      };
      if (this.selectedItems.length > 0) {
        queryParams.requirementTypeId = this.selectedItems.map(item => item.productTypeId).join(',');
      }

      requirementPage(queryParams).then(res => {
        if(res.code === 200){
          this.cardList = res.rows
          this.total = res.total
        }
      })
    }
  }

}
</script>

<style scoped>
/deep/.el-textarea.is-disabled .el-textarea__inner {
  color: #606266;
}
.advertisement{
  width: 252px;
  height: 284px;
  background-image: url('~@/assets/image/advertisement.png');
  background-size: 100% 100%;
  position: relative;
}
.requirment{
  position: absolute;
  top: 50px;
  right: 220px;
  z-index: 1000;
}
.top-container{
  width: 100%;
  height: 400px;
  background: #fff;
  background-size: cover;
  position: relative;
  margin-top: 2px;
}
.left-border{
    border-left: 3px solid #436AF7;
}
.pl300{
  padding-left: 15%;
}
.pr300{
  padding-right: 15%;
}
.homeContent{
    width: 100%;
    min-height:80vh;
    margin: 0 auto;
}
.border{
    border: 1px solid #ccc;
}
.shopTypeCard{
  flex: 0 0 calc((100%  - 125px) / 6);
  aspect-ratio: 3 / 1; /* 宽高比为3:1 */
  box-sizing: border-box;
  background-size: 100% 100%;
  border-radius: 5px 5px 5px 5px;
  color: #436AF7;
  align-items: center;
}
.shopTypeCard:nth-child(n) {
  margin-right: 25px;
}
.shopTypeCard:nth-child(6n) {
  margin-right: 0px;
}
.card-detail{
  background-image: url('~@/assets/image/type_detail.png');
  background-size: 100% 100%;
  height: 140px;
  width: 100%;
}
.card-title{
  width: 158px;
  height: 45px;
  font-size: 16px;
  font-weight: bold;
  color: #fff;
  background-image: url('~@/assets/image/cardTitle.png');
  padding: 12px;
}
.card-content{
  background: rgb(240,243,255);
  height: 100px;
  padding: 25px 20px 25px 30px
}
.selected {
  background-image: url('~@/assets/image/typebgs1.png');
  background-size: 100% 100%;
  color: #FFFFFF;
}
.selectedText {
  color: #333;
}
.button1{
  background: #FFFFFF;
  border-radius: 20px;
  border: 1px solid #436AF7;
  color: #436AF7;
  font-size: 18px;
  margin-right:40px;
  position: absolute;
  bottom: 20px;
  left: 30%;
}

 .background1 {
  background-image: url('~@/assets/image/typebg1.png');
  background-size: 100% 100%;
  }
 .backgrounds1 {
  background-image: url('~@/assets/image/typebgs1.png');
  background-size: 100% 100%;
  color: #FFFFFF;
  }
 .background2 {
  background-image: url('~@/assets/image/typebg2.png');
   background-size: 100% 100%;
  }
 .backgrounds2 {
  background-image: url('~@/assets/image/typebgs2.png');
  background-size: 100% 100%;
  color: #FFFFFF;
  }
  .background3 {
  background-image: url('~@/assets/image/typebg3.png');
   background-size: 100% 100%;
  }
 .backgrounds3 {
  background-image: url('~@/assets/image/typebgs3.png');
  background-size: 100% 100%;
  color: #FFFFFF;
  }
  .background4 {
  background-image: url('~@/assets/image/typebg4.png');
  background-size: 100% 100%;
  }
  .backgrounds4 {
  background-image: url('~@/assets/image/typebgs4.png');
  background-size: 100% 100%;
  color: #FFFFFF;
  }
  .background5 {
  background-image: url('~@/assets/image/typebg5.png');
  background-size: 100% 100%;
  }
  .backgrounds5 {
  background-image: url('~@/assets/image/typebgs5.png');
  background-size: 100% 100%;
  color: #FFFFFF;
  }
  .background6 {
  background-image: url('~@/assets/image/typebg6.png');
  background-size: 100% 100%;
  }
  .backgrounds6 {
  background-image: url('~@/assets/image/typebgs6.png');
  background-size: 100% 100%;
  color: #FFFFFF;
  }
  .background7 {
  background-image: url('~@/assets/image/typebg7.png');
  background-size: 100% 100%;
  }
  .backgrounds7 {
  background-image: url('~@/assets/image/typebgs7.png');
  background-size: 100% 100%;
  color: #FFFFFF;
  }
  .background8 {
  background-image: url('~@/assets/image/typebg8.png');
  background-size: 100% 100%;
  }
  .backgrounds8 {
  background-image: url('~@/assets/image/typebgs8.png');
  background-size: 100% 100%;
  color: #FFFFFF;
  }
  .background9 {
  background-image: url('~@/assets/image/typebg9.png');
  background-size: 100% 100%;
  }
  .backgrounds9 {
  background-image: url('~@/assets/image/typebgs9.png');
  background-size: 100% 100%;
  color: #FFFFFF;
  }
  .background10 {
  background-image: url('~@/assets/image/typebg10.png');
  background-size: 100% 100%;
  }
  .backgrounds10 {
  background-image: url('~@/assets/image/typebgs10.png');
  background-size: 100% 100%;
  color: #FFFFFF;
  }
  .productImage{
    width:100%;
    aspect-ratio: 1.5 / 1;
    display:flex;
    justify-content:center;
    align-items:center;
    background-image: url('~@/assets/image/productBg.png');
    background-size: 100% 100%;
  }
</style>
